<?php
namespace app\index\logic;
use app\classes\helper\AdvertBehavior;
use think\Db;

class User
{

    /*
     * 阅读扣币
     * */
    public function readCost($chapterInfo,$params)
    {
        $uInfo = $this->getInfo();

        if( strlen($uInfo['vip_date']) > 1 && strtotime($uInfo['vip_date']) >= time() )
        {
            $chapterInfo['is_pay'] = 0;
        }

        $uid = request()->userInfo['id'];

        //消费凭证检测
        $SaleHistoryLogic = \think\facade\App::model('SaleHistory', 'logic');
        $checkResult = $SaleHistoryLogic->checkConsume($uid,$params['nid'],$params['chapter_no']);
        if($checkResult)
        {
            $chapterInfo['is_pay'] = 0;
        }

        if($chapterInfo['is_pay'] < 1)
        {
            return ['code'=>0,'msg'=>'该章节为免费章节','is_pay'=>$chapterInfo['is_pay'],'used_point' => 0, 'used_coin' => 0];
        }

        $spend_ficoin = $chapterInfo['spend_ficoin'];

        $UserModel = \think\facade\App::model('User', 'model');
        $UserPointsLogic = \think\facade\App::model('UserBookPoints', 'logic');
        $book_point = $UserPointsLogic->getBalance($uid);

        Db::startTrans();
        try {

            if($book_point >= $spend_ficoin)
            {
                $UserPointsLogic->consume($uid,$spend_ficoin);
                $used_point = $spend_ficoin; //使用书点
                $used_coin = 0; //使用书币
            }else{
                //查询用户书币余额
                $balance = $uInfo['book_coin'] + $book_point;
                if ($balance >= $spend_ficoin) {
                    /**
                     * 书币加书点够支付
                     */
                    $used_point = 0;
                    $used_coin = $spend_ficoin;
                    if ($book_point) {
                        $used_coin = $UserPointsLogic->consume($uid, $spend_ficoin);
                        $used_point = $spend_ficoin - $used_coin;
                    }
                    $book_coin = $uInfo['book_coin'] - $used_coin;
                    $UserModel->updateRecord(['id'=>$uid],['book_coin'=>$book_coin]);

                }else{
                    return ['code'=>12,'msg'=>'用户余额不足'];
                }
            }

            $userConsume = Db::table('quick_user_consume')->where('uid',$uid)
                            ->field('used_all,used_point,used_coin')->findOrEmpty();
            if($userConsume)
            {
                $consume['used_all']    = $userConsume['used_all']+$spend_ficoin;
                $consume['used_point']  = $userConsume['used_point']+$used_point;
                $consume['used_coin']   = $userConsume['used_coin']+$used_coin;
                Db::table('quick_user_consume')->where('uid',$uid)->update($consume);
            }else{
                $consume['uid']         = $uid;
                $consume['used_all']    = $spend_ficoin;
                $consume['used_point']  = $used_point;
                $consume['used_coin']   = $used_coin;
                Db::table('quick_user_consume')->insert($consume);
            }

            $result = ['code'=>0,'msg'=>'扣币成功','is_pay'=>$chapterInfo['is_pay'],'used_point' => $used_point, 'used_coin' => $used_coin];

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {

            $result = ['code'=>102,'msg'=>"扣费失败：line:{$e->getLine()},msg:{$e->getMessage()}"];
            // 回滚事务
            Db::rollback();
        }

        return $result;

    }

    /*用户个人资料获取*/
    public function getInfo()
    {
        $UserModel = \think\facade\App::model('User', 'model');
        $record = $UserModel->getOne(['id'=>request()->userInfo['id']],'id as uid,email,book_coin,vip_exp_time,sign_days,source_quick_id');
        $data = [];

        if($record)
        {

            $UserInfoModel = \think\facade\App::model('UserInfo', 'model');
            $uInfo = $UserInfoModel->getOne(['id'=>request()->userInfo['id']],'id,nickname',$record['source_quick_id']);

            $time_now = time();
            $book_point = Db::table('quick_user_book_points')->where('uid',$record['uid'])
                ->where('overdue_time','>',$time_now)->sum('book_point');

            $data['vip_date']     = $record['vip_exp_time'] >= time() ? date('Y-m-d H:i:s',$record['vip_exp_time']) : '';
            $data['book_point']   = $book_point;
            $data['virtual_currency'] = $record['book_coin'];
            $data['book_coin'] = $record['book_coin'];
            $data['sign_days'] = $record['sign_days'];
            $data['nickname'] = $uInfo['nickname'];
            $data['uid'] = $record['uid'];
			$data['email'] = $record['email'];

        }

        return $data;
    }

    /*用户登录*/
    public function sign_in_app($params)
    {
        $UserModel = \think\facade\App::model('User', 'model');
        $UserInfoModel = \think\facade\App::model('UserInfo', 'model');
        $info = $UserModel->getOne(['device_id' => $params['device_id']],'id,agent_id,source_agent_id,source_quick_id,book_coin,vip_exp_time');

        if ($info) {

            $tokenLogic = \think\facade\App::model('Token', 'logic');
            $result = $tokenLogic->writeToken($info['id']);
            if ($result['code'] != 0) {
                return ['code' => 102, 'msg' => '登录凭证写入失败'];
            }

            $provider = isset($params['provider']) ? $params['provider'] : '';

            $where[] = ['id','=',$info['id']];
            $res = $UserModel->updateRecord($where,[
                'agent_id'=>request()->agentId,'channel_id'=>request()->channelId,
                'quick_id'=>request()->quickAppId,'provider'=>$provider
            ]);

            if($res)
            {

                $record = $UserInfoModel->getOne(['id'=>$info['id']],'id,nickname',request()->quickAppId);
                if(empty($record))
                {
                    $data_info['nickname']      = $this->createNickName();
                    $data_info['device_id']     = $params['device_id'];

                    $UserInfoModel->insertRecord($data_info,request()->quickAppId);
                }

                $time_now = time();

                $book_point = Db::table('quick_user_book_points')->where('uid',$info['id'])
                    ->where('overdue_time','<',$time_now)->sum('book_point');

                $ReadHistoryModel = \think\facade\App::model('ReadHistory', 'logic');

                $reqData['id']                  = (int) $info['id'];
                $reqData['nickname']            = $record ? $record['nickname'] : $data_info['nickname'];
                $reqData['token']               = $result['data'];
                $reqData['virtual_currency']    = $info['book_coin'];
                $reqData['book_point']          = $book_point;
                $reqData['vip_date']            = $info['vip_exp_time'] >= time() ? date('Y-m-d H:i:s',$info['vip_exp_time']) : '';
                $reqData['recent_reading']      = $ReadHistoryModel->getRecentRecord($info['id']);


                $result = ['code' => 0, 'msg' => 'success', 'data' =>$reqData];
            }else{
                $result = ['code' => 102, 'msg' => '用户数据更新失败'];
            }

        } else {
            $result = $this->addUserInfo($params, $UserModel, $UserInfoModel,'app');
            if($result['code'] < 1)
            {
                $AdvertBehavior = new AdvertBehavior();
                $AdvertBehavior->writeRecord($result['data']['id'],request()->channelId);

            }
        }

        return $result;
    }
	
	/**邮件地址登录*/
	public function sign_in_email($params)
	{
		
		$info = Db::table('quick_user')->where('device_id',$params['device_id'])->field('email,id,agent_id,source_agent_id,source_quick_id,book_coin,vip_exp_time')->findOrEmpty();
		
		if(empty($info))
		{
			return ['code' => 102, 'msg' => 'Visitor information does not exist'];
		}
			
		$has_email = Db::table('quick_user')->where('email',$params['email'])->field('id')->findOrEmpty();
		
		if($params['is_bind'] == 2)
		{
			if(strlen($info['email']) > 1 && $info['email'] != $params['email'])
			{
				return ['code' => 102, 'msg' => 'The email address is incorrect. Please verify and re-enter'];
			}
			if(!empty($has_email))
			{
				$info = Db::table('quick_user')->where('id',$has_email['id'])->field('email,id,agent_id,source_agent_id,source_quick_id,book_coin,vip_exp_time')->findOrEmpty();
			}
		}else{
			
			if(!empty($has_email))
			{
				return ['code' => 106, 'msg' => 'The email address has already been bound. Please do not bind it again'];
				/*$tokenLogic = \think\facade\App::model('Token', 'logic');
				$resultToken = $tokenLogic->writeToken($has_email['id']);
				if ($resultToken['code'] != 0) {
					return ['code' => 102, 'msg' => 'Login credentials writing failed'];
				}
				
				$info = Db::table('quick_user')->where('id',$has_email['id'])->field('email,id,agent_id,source_agent_id,source_quick_id,book_coin,vip_exp_time')->findOrEmpty();
			
				$token = $resultToken['data'];*/
			}
			
		}
		
		
		$token = '';
		if($params['is_bind'] == 2)
		{
			$tokenLogic = \think\facade\App::model('Token', 'logic');
			$resultToken = $tokenLogic->writeToken($info['id']);
			if ($resultToken['code'] != 0) {
				return ['code' => 102, 'msg' => 'Login credentials writing failed'];
			}
			
			$token = $resultToken['data'];
			
			if(empty($has_email) && strlen($info['email']) < 1)
			{
				
				Db::table('quick_user')->where('device_id',$params['device_id'])->update(['email'=>$params['email']]);
				Db::table('quick_user_'.$info['source_quick_id'])->where('id',$info['id'])->update(['email'=>$params['email']]);		
			}
			
		}else{
			Db::table('quick_user')->where('device_id',$params['device_id'])->update(['email'=>$params['email']]);
			Db::table('quick_user_'.$info['source_quick_id'])->where('id',$info['id'])->update(['email'=>$params['email']]);
		}
		
		$UserInfoModel = \think\facade\App::model('UserInfo', 'model');
		$record = $UserInfoModel->getOne(['id'=>$info['id']],'id,nickname',$info['source_quick_id']);	
		
		$time_now = time();

		$book_point = Db::table('quick_user_book_points')->where('uid',$info['id'])
			->where('overdue_time','<',$time_now)->sum('book_point');

		$ReadHistoryModel = \think\facade\App::model('ReadHistory', 'logic');

		$reqData['id']                  = (int) $info['id'];
		$reqData['nickname']            = $record ? $record['nickname'] : $data_info['nickname'];
		$reqData['token']               = $token;
		$reqData['virtual_currency']    = $info['book_coin'];
		$reqData['book_point']          = $book_point;
		$reqData['vip_date']            = $info['vip_exp_time'] >= time() ? date('Y-m-d H:i:s',$info['vip_exp_time']) : '';
		$reqData['recent_reading']      = $ReadHistoryModel->getRecentRecord($info['id']);


		$result = ['code' => 0, 'msg' => 'success', 'data' =>$reqData];

        return $result;
	}

    /*用户数据写入*/
    public function addUserInfo($params, $UserModel, $UserInfoModel, $platform)
    {
        $data['quick_id']           = request()->quickAppId;
        $data['agent_id']           = request()->agentId;
        $data['channel_id']         = request()->channelId;
        $data['device_id']          = $params['device_id'];
        $data['source_quick_id']    = request()->quickAppId;
        $data['source_agent_id']    = request()->agentId;
        $data['source_channel_id']  = request()->channelId;
        $data['source_novel_id']    = request()->nid;
        $data['regdate']            = date('Y-m-d');
        $data['regtime']            = date('Y-m-d H:i:s');
        $data['login_time']         = date('Y-m-d H:i:s');
        $data['provider']           = isset($params['provider']) ? $params['provider'] : '';
        $data['ip_addr']            = request()->ip();
		$data['email'] 				= isset($params['email']) ? $params['email'] : '';

        $data_info['nickname']      = $this->createNickName();
        $data_info['device_id']     = $params['device_id'];
		$data_info['email'] 	    = isset($params['email']) ? $params['email'] : '';

        $result = true;
        Db::startTrans();
        try {

            $uid = $UserModel->insertRecord($data);
            $data_info['id'] = $uid;
            $UserInfoModel->insertRecord($data_info,request()->quickAppId);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {

            $result = false;
            // 回滚事务
            Db::rollback();
        }

        if($result){

            $tokenLogic = \think\facade\App::model('Token', 'logic');
            $resultToken = $tokenLogic->writeToken($uid);

            if ($resultToken['code'] != 0) {
                return ['code' => 102, 'msg' => '登录凭证写入失败'];
            }

            $reqData['id']          = (int) $uid;
            $reqData['nickname']    = $data_info['nickname'];
            $reqData['token']       = $resultToken['data'];
            $reqData['virtual_currency'] = 0;
            $reqData['book_point']      = 0;
            $reqData['vip_date']        = '';
            $reqData['recent_reading']  = [];

            //判断当前应用版本是否开启审核事件
            $audit_event = Db::table('quick_audit_event')->where('status',1)
                ->where('delete_time','<',1)
                ->where('api_version',request()->version)
                ->field('id')->findOrEmpty();

            if($audit_event)
            {
                $data_qa['userId']      = $data['device_id'];
                $data_qa['event_id']    = $audit_event['id'];
                $data_qa['api_version'] = request()->version;
                $data_qa['quick_id']    = request()->quickAppId;
                $data_qa['uid']         = $uid;
                $data_qa['provider']    = $data['provider'];
                $data_qa['ip']          = $data['ip_addr'];

                Db::table('quick_auditor')->insert($data_qa);
                Db::table('quick_ips')->insert(['lib_id'=>1,'ip'=>$data['ip_addr']]);
            }

            return ['code'=>0,'msg'=>'success','data'=>$reqData];
        }else{
            return ['code' => 102, 'msg' => '用户数据写入失败'];
        }
    }

    /*生成随机昵称*/
    private function createNickName()
    {
        return getNonceStr(6) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

}